package com.jch.webstatic;

import com.jch.webstatic.handler.StaticWebHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

// Netty 实现静态WEB服务器
public class WebStaticServer {


    private Properties props;

    public WebStaticServer(Properties props) {
        this.props = props;
    }

    private void startServer() {
        int port = Integer.parseInt(props.getProperty("port").trim());
        String pagePath = props.getProperty("pagePath");

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 512)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    // 初始化通道
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        // HttpRequestDecoder 解码器 、HttpResponseEncoder 编码器
                        p.addLast(new HttpServerCodec());
                        // 聚合HttpMessage及之后的HttpContent 为 FullHttpRequest或FullHttpResponse 对象（取决于请求或响应操作）
                        p.addLast(new HttpObjectAggregator(1024 * 1024));
                        // 大数据分块处理器
                        p.addLast(new ChunkedWriteHandler());

                        // 静态web信息处理器
                        p.addLast(new StaticWebHandler(pagePath));
                    }
                });
        try {
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            System.out.println("web static server start done.");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("web static server stop.");
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws IOException {
        String configPath = WebStaticServer.class.getResource("/config.properties").getPath();
        System.out.println("加载配置文件路径：" + configPath);
        InputStream inputStream = new FileInputStream(configPath);
        Properties properties = new Properties();
        properties.load(inputStream);
        new WebStaticServer(properties).startServer();
    }

}
